package com.leetcode.p200;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Test216 {

    private List<List<Integer>> res   = new ArrayList<>();
    private Deque<Integer>      stack = new LinkedList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {

        help(k, n, 1, 0);

        return res;
    }

    private void help(int k, int n, int begin, int sum) {
        if (stack.size() == k && sum == n) {
            res.add(new ArrayList<>(stack));
            return;
        }

        for (int i = begin; i <= 9; i++) {
            sum += i;

            if (sum > n) {
                return;
            }
            stack.addLast(i);

            help(k, n, i + 1, sum);

            sum -= i;
            stack.removeLast();
        }
    }

    public static void main(String[] args) {

        Test216 test = new Test216();
//        System.out.println(test.combinationSum3(3, 7));
        System.out.println(test.combinationSum3(3, 9));
    }

}
